﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using WHW_NetUtility;
//using HalconDotNet;
using TIS.Imaging;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using MotionControl;
using System.Diagnostics;
using CameraAcq;
using System.Threading.Tasks;

namespace MainFrame
{
    public partial class FormCalibration : Form
    {
        const int suckerRotationNum = 6;

        string path_cameraSetup="";//相机设置路径
        string readImagePath = "";//读入的图像路径
        string saveImagefolder = "";//保存图像的文件夹
        string saveImagePath = "";//保存图像的路径
        string calibFilePath="camera.cal";//标定文件路径
        int stationNum = 0;//工站选择
        string[] cameraInfo_cbo;
        private List<CamInfo> imagelist=new List<CamInfo>();

        int m_exposureTime = 10000;//曝光时间
        float m_gain = 1.0f;//增益
        float m_frame = 10f;//帧率
        float m_rotateAngle = 0;//旋转角度


        private CalibrationData calib_F=new CalibrationData();
        private CalibrationData calib_L = new CalibrationData();
        private CalibrationData calib_M = new CalibrationData();

        bool first_cbx = false;
        private double PixelToReal;

        public FormCalibration()
        {
            path_cameraSetup = Environment.CurrentDirectory + "\\camera.xml";
            InitializeComponent();
        }

        private void btn_Calibrate_Click(object sender, EventArgs e)
        {
            double[] resultD = ImageToReal();
            tbx_camCaliAngle.Text = Math.Acos(resultD[0]).ToString("#0.000");
            tbx_imageOriginX.Text = resultD[2].ToString("#0.000");
            tbx_imageOriginY.Text = resultD[3].ToString("#0.000");
            if (tbx_imageOriginX.Text != "0.000" && tbx_imageOriginX.Text != "非数字")
            {
                ControlToClass(stationNum);
            }
        }

        private void btn_selectImageFolder_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog saveFolder = new FolderBrowserDialog();
                saveFolder.Description = "图像存放路径";
                //AMtype_FBD.RootFolder = Environment.SpecialFolder.MyComputer;
                saveFolder.RootFolder = System.Environment.SpecialFolder.MyComputer;
                if (saveFolder.ShowDialog() == DialogResult.OK)
                {
                    saveImagefolder = saveFolder.SelectedPath ;
                    tbx_savePath.Text = saveImagefolder;
                    displalyInfo.displayInfoMain("图像保存路径选择成功，型号路径为：" +saveImagefolder);
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("图像保存路径未选择：" +ex.Message);
                Log4Helper.WriteLog("FormCalibration.selectImageFolder", ex);
            }
        }

        private void FormCalibration_Load(object sender, EventArgs e)
        {
            try
            {              
                //DeserializeFile();
                //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Fweld.cameraSerial))
                //{
                //    if (GlobalImage.hik_Fweld==null)
                //    {
                //        GlobalImage.hik_Fweld = new HikVision(GlobalImage.cablibData_Fweld.cameraSerial);
                //        GlobalImage.hik_Fweld.imageOut = visionProc.Fweld;
                //    }                    
                //}
                //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Lweld.cameraSerial))
                //{
                //    if (GlobalImage.hik_Lweld==null)
                //    {
                //        GlobalImage.hik_Lweld = new HikVision(GlobalImage.cablibData_Lweld.cameraSerial);
                //        GlobalImage.hik_Lweld.imageOut = visionProc.Lweld;
                //    }
                //}
                //if (!string.IsNullOrEmpty(GlobalImage.cablibData_Measure.cameraSerial))
                //{
                //    if (GlobalImage.hik_Meausre==null)
                //    {
                //        GlobalImage.hik_Meausre = new HikVision(GlobalImage.cablibData_Measure.cameraSerial);
                //        GlobalImage.hik_Meausre.imageOut = visionProc.measure;
                //    }
                   
                //}
                //if (GlobalValp.pGlobalVar.OperLevel==(int)GlobalValp.pGlobalVar.operLevel.user)
                //{
                //    cbx_camSerialSelect.Enabled= false;
                //    cbo_cameraSerial.Enabled = false;
                //}
                //else
                //{
                //    cbx_camSerialSelect.Enabled = true;
                //    cbo_cameraSerial.Enabled = true;
                //}
                //rbn_stationFweld.Checked = true;//初始化时选中前焊接工位
                ////saveImagefolder = AppDomain.CurrentDomain.BaseDirectory;//保存图像文件夹
                //tbx_savePath.Text = saveImagefolder;
                //tbx_saveTime.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                //tbx_readPath.Text = saveImagefolder;

                //GlobalImage.getCamera = new HikVision(DeviceType.HikVision);
                //GlobalImage.getCamera.AcqDeviceList(ref imagelist);
                //cameraInfo_cbo = new string[imagelist.Count];
                //for (int i = 0; i < imagelist.Count; i++)
                //{
                //    GlobalImage.camSerialNo[i] = imagelist[i].m_SerialNO;
                //    cbo_cameraSerial.Items.Add(imagelist[i].m_SerialNO + " (" + imagelist[i].m_UserDefineName + " ：" + imagelist[i].m_CamName + ")");
                //    cameraInfo_cbo[i] = imagelist[i].m_SerialNO + " (" + imagelist[i].m_UserDefineName + " ：" + imagelist[i].m_CamName + ")";
                //}

                //if (imagelist.Count != 0)
                //{
                //    cbo_cameraSerial.SelectedIndex = 0;
                //    displalyInfo.displayInfoMain("找到 " + imagelist.Count.ToString() + " 个相机！");
                //}
                //else
                //{
                //    displalyInfo.displayInfoMain("没有找到相机！");
                //}

                //stationSelect();
                //ClassToControl(stationNum);

                //if (rbn_grabContunial.Checked)
                //{
                //    GlobalImage.hik_Fweld.SetTriggerMode(TriggerMode.continual);
                //    btn_SoftTrigger.Enabled = false;
                //}
                //else
                //{
                //    GlobalImage.hik_Fweld.SetTriggerMode(TriggerMode.softTrigger);
                //    btn_SoftTrigger.Enabled = true;
                //}

                
                //displalyInfo.displayInfoMain("标定初始化完成！");
            }
            catch (System.Exception)
            {
                //displalyInfo.displayInfoMain("标定初始化错误" + ex.Message);
            }
           
            //GlobalImage.cablibData_Fweld.cameraSerial = cbo_cameraSerial.SelectedItem.ToString().Trim().Substring(0, cbo_cameraSerial.SelectedItem.ToString().Trim().IndexOf("(") - 1);
        }

        public void rbnControlChecked(GroupBox gb, out string rbnText)
        {
            rbnText = "";
            foreach (var item in gb.Controls)
            {
                if (item is RadioButton)
                {
                    if (((RadioButton)item).Checked)
                    {
                        rbnText = ((RadioButton)item).Text;
                        break;
                    }
                }
            }
        }

        private void ControlToClass(int satation)
        {
            switch (satation)
            {
                case 0:
                   singleControlToPara(GlobalImage.cablibData_Fweld) ;
                    break;
                case 1:
                    singleControlToPara(GlobalImage.cablibData_Lweld);
                    break;
                case 2:
                    singleControlToPara(GlobalImage.cablibData_Measure);
                    break;
                default:
                    break;
            }
            
        }

        private void singleControlToPara(CalibrationData temp)
        {
            try
            {
                #region 相机参数

                //mark点坐标
                temp.mark1X = Convert.ToDouble(tbx_Mark1RealX.Text.Trim());//mark1点X实际坐标
                temp.mark1Y = Convert.ToDouble(tbx_Mark1RealY.Text.Trim());//mark1点Y实际坐标
                temp.mark2X = Convert.ToDouble(tbx_Mark2RealX.Text.Trim());//mark2点X实际坐标
                temp.mark2Y = Convert.ToDouble(tbx_Mark2RealY.Text.Trim());//mark2点Y实际坐标

                //标定结果
                temp.calibAngle = Convert.ToDouble(tbx_camCaliAngle.Text.Trim());//相机旋转角度
                temp.pixPerReal = Convert.ToDouble(tbx_camCaliPixelReal.Text.Trim());//像素实际值，倍率
                temp.imageOriginX = Convert.ToDouble(tbx_imageOriginX.Text.Trim());//图像原点在实际坐标系中的位置X
                temp.imageOriginY = Convert.ToDouble(tbx_imageOriginY.Text.Trim());//图像原点在实际坐标系中的位置Y

                //相机参数
                temp.exposure = Convert.ToInt32(tbx_exposureSetup.Text.Trim());//曝光时间
                temp.gain = Convert.ToDouble(tbx_gain.Text.Trim());//增益
                temp.frame = Convert.ToDouble(tbx_frame.Text.Trim());//帧率
                //成像变换;
                temp.isHorizontalFlip = cbx_HorizontalFlip.Checked;//水平镜像
                temp.isVerticalFlip = cbx_VerticalFlip.Checked;//垂直镜像
                temp.imageRotateAngle = Convert.ToDouble(tbx_rotateAngle.Text.Trim());//图像旋转角度
                //采集模式
                temp.isGrabContinual = rbn_grabContunial.Checked;//采集模式
                temp.saveFilePath = tbx_savePath.Text.Trim();//保存路径

                string imageFormat = "";
                rbnControlChecked(gbx_saveImageFormat, out imageFormat);//查找gbx_burnishAxis组件，并输出选中的radioButton的文本
                switch (imageFormat.Trim())
                {
                    case "bmp":
                        temp.saveImageFormat = (int)ImageSaveFormat.bmp;
                        break;
                    case "jpg":
                        temp.saveImageFormat = (int)ImageSaveFormat.jpg;
                        break;
                    case "png":
                        temp.saveImageFormat = (int)ImageSaveFormat.png;
                        break;
                    case "tiff":
                        temp.saveImageFormat = (int)ImageSaveFormat.tiff;
                        break;
                    default:
                        temp.saveImageFormat = (int)ImageSaveFormat.bmp;
                        break;
                }
                if (GlobalVar.isUpdateCamSerial)
                {
                    GlobalVar.isUpdateCamSerial = false;
                    temp.cameraSerialFull = cbo_cameraSerial.SelectedItem.ToString().Trim();
                    temp.cameraSerial = cbo_cameraSerial.SelectedItem.ToString().Trim().Substring(0, cbo_cameraSerial.SelectedItem.ToString().Trim().IndexOf("(") - 1);
                }
                #endregion

            }
            catch (Exception ex)
            {
                MessageBox.Show("输入错误，请检查" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormCalibration.ControlToClass", ex);
            }
        }
        private void ClassToControl(int satation)
        {
            switch (satation)
            {
                case 0:
                    singleParaToControl(GlobalImage.cablibData_Fweld);
                    break;
                case 1:
                    singleParaToControl(GlobalImage.cablibData_Lweld);
                    break;
                case 2:
                    singleParaToControl(GlobalImage.cablibData_Measure);
                    break;
                default:
                    break;
            }           
        }

        private void singleParaToControl(CalibrationData temp)
        {
            try
            {
                #region 相机参数
                //mark点坐标
                tbx_Mark1RealX.Text = temp.mark1X.ToString();//mark1点X实际坐标
                tbx_Mark1RealY.Text = temp.mark1Y.ToString();//mark1点Y实际坐标
                tbx_Mark2RealX.Text = temp.mark2X.ToString();//mark2点X实际坐标
                tbx_Mark2RealY.Text = temp.mark2Y.ToString();//mark2点Y实际坐标

                //标定结果
                tbx_camCaliAngle.Text = temp.calibAngle.ToString();//相机旋转角度
                tbx_camCaliPixelReal.Text = temp.pixPerReal.ToString();//像素实际值，倍率
                tbx_imageOriginX.Text = temp.imageOriginX.ToString();//图像原点在实际坐标系中的位置X
                tbx_imageOriginY.Text = temp.imageOriginY.ToString();//图像原点在实际坐标系中的位置Y

                //相机参数
                tbx_exposureSetup.Text = temp.exposure.ToString();//曝光时间
                tbx_gain.Text = temp.gain.ToString();//增益
                tbx_frame.Text = temp.frame.ToString();//帧率
                //成像变换;
                cbx_HorizontalFlip.Checked = temp.isHorizontalFlip;//水平镜像
                cbx_VerticalFlip.Checked = temp.isVerticalFlip;//垂直镜像
                tbx_rotateAngle.Text = temp.imageRotateAngle.ToString();//图像旋转角度
                //采集模式
                rbn_grabContunial.Checked = temp.isGrabContinual;//采集模式
                rbn_grabTrigger.Checked = !temp.isGrabContinual;
                tbx_savePath.Text = temp.saveFilePath;//保存路径

                string imageFormat = "";
                rbnControlChecked(gbx_saveImageFormat, out imageFormat);//查找gbx_burnishAxis组件，并输出选中的radioButton的文本
                switch (temp.saveImageFormat)
                {
                    case (int)ImageSaveFormat.bmp:
                        rbn_ImageFormat_bmp.Checked = true;
                        break;
                    case (int)ImageSaveFormat.jpg:
                        rbn_ImageFormat_jpg.Checked = true;
                        break;
                    case (int)ImageSaveFormat.png:
                        rbn_ImageFormat_png.Checked = true;
                        break;
                    case (int)ImageSaveFormat.tiff:
                        rbn_ImageFormat_tiff.Checked = true;
                        break;
                    default:
                        break;
                }
                if (!string.IsNullOrEmpty(temp.cameraSerial))
                {
                    int index = cbo_cameraSerial.FindString(temp.cameraSerialFull);
                    cbo_cameraSerial.SelectedIndex = index;
                }
                #endregion

            }
            catch (Exception ex)
            {
                MessageBox.Show("输入错误，请检查" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormCalibrationControlToClass", ex);
            }
        }
        //private void singleParaToControl_L()
        //{
        //    try
        //    {
        //        #region 相机参数
        //        //mark点坐标
        //        tbx_Mark1RealX.Text = calib_L.mark1X.ToString();//mark1点X实际坐标
        //        tbx_Mark1RealY.Text = calib_L.mark1Y.ToString();//mark1点Y实际坐标
        //        tbx_Mark2RealX.Text = calib_L.mark2X.ToString();//mark2点X实际坐标
        //        tbx_Mark2RealY.Text = calib_L.mark2Y.ToString();//mark2点Y实际坐标

        //        //标定结果
        //        tbx_camCaliAngle.Text = calib_L.calibAngle.ToString();//相机旋转角度
        //        tbx_camCaliPixelReal.Text = calib_L.pixPerReal.ToString();//像素实际值，倍率
        //        tbx_imageOriginX.Text = calib_L.imageOriginX.ToString();//图像原点在实际坐标系中的位置X
        //        tbx_imageOriginY.Text = calib_L.imageOriginY.ToString();//图像原点在实际坐标系中的位置Y

        //        //相机参数
        //        tbx_exposureSetup.Text = calib_L.exposure.ToString();//曝光时间
        //        tbx_gain.Text = calib_L.gain.ToString();//增益
        //        tbx_frame.Text = calib_L.frame.ToString();//帧率
        //        //成像变换;
        //        cbx_HorizontalFlip.Checked = calib_L.isHorizontalFlip;//水平镜像
        //        cbx_VerticalFlip.Checked = calib_L.isVerticalFlip;//垂直镜像
        //        tbx_rotateAngle.Text = calib_L.imageRotateAngle.ToString();//图像旋转角度
        //        //采集模式
        //        rbn_grabContunial.Checked = calib_L.isGrabContinual;//采集模式
        //        rbn_grabTrigger.Checked = !calib_L.isGrabContinual;
        //        tbx_savePath.Text = calib_L.saveFilePath;//保存路径

        //        string imageFormat = "";
        //        rbnControlChecked(gbx_saveImageFormat, out imageFormat);//查找gbx_burnishAxis组件，并输出选中的radioButton的文本
        //        switch (calib_L.saveImageFormat)
        //        {
        //            case (int)ImageSaveFormat.bmp:
        //                rbn_ImageFormat_bmp.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.jpg:
        //                rbn_ImageFormat_jpg.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.png:
        //                rbn_ImageFormat_png.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.tiff:
        //                rbn_ImageFormat_tiff.Checked = true;
        //                break;
        //            default:
        //                break;
        //        }
        //        if (!string.IsNullOrEmpty(calib_F.cameraSerial))
        //        {
        //            int index = cbo_cameraSerial.FindString(calib_L.cameraSerialFull);
        //            cbo_cameraSerial.SelectedIndex = index;
        //        }
        //        #endregion

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("输入错误，请检查" + Environment.NewLine + ex.Message);
        //        Log4Helper.WriteLog("FormCalibrationControlToClass", ex);
        //    }
        //}
        //private void singleParaToControl_M()
        //{
        //    try
        //    {
        //        #region 相机参数
        //        //mark点坐标
        //        tbx_Mark1RealX.Text = calib_M.mark1X.ToString();//mark1点X实际坐标
        //        tbx_Mark1RealY.Text = calib_M.mark1Y.ToString();//mark1点Y实际坐标
        //        tbx_Mark2RealX.Text = calib_M.mark2X.ToString();//mark2点X实际坐标
        //        tbx_Mark2RealY.Text = calib_M.mark2Y.ToString();//mark2点Y实际坐标

        //        //标定结果
        //        tbx_camCaliAngle.Text = calib_M.calibAngle.ToString();//相机旋转角度
        //        tbx_camCaliPixelReal.Text = calib_M.pixPerReal.ToString();//像素实际值，倍率
        //        tbx_imageOriginX.Text = calib_M.imageOriginX.ToString();//图像原点在实际坐标系中的位置X
        //        tbx_imageOriginY.Text = calib_M.imageOriginY.ToString();//图像原点在实际坐标系中的位置Y

        //        //相机参数
        //        tbx_exposureSetup.Text = calib_M.exposure.ToString();//曝光时间
        //        tbx_gain.Text = calib_M.gain.ToString();//增益
        //        tbx_frame.Text = calib_M.frame.ToString();//帧率
        //        //成像变换;
        //        cbx_HorizontalFlip.Checked = calib_M.isHorizontalFlip;//水平镜像
        //        cbx_VerticalFlip.Checked = calib_M.isVerticalFlip;//垂直镜像
        //        tbx_rotateAngle.Text = calib_M.imageRotateAngle.ToString();//图像旋转角度
        //        //采集模式
        //        rbn_grabContunial.Checked = calib_M.isGrabContinual;//采集模式
        //        rbn_grabTrigger.Checked = !calib_M.isGrabContinual;
        //        tbx_savePath.Text = calib_M.saveFilePath;//保存路径

        //        string imageFormat = "";
        //        rbnControlChecked(gbx_saveImageFormat, out imageFormat);//查找gbx_burnishAxis组件，并输出选中的radioButton的文本
        //        switch (calib_M.saveImageFormat)
        //        {
        //            case (int)ImageSaveFormat.bmp:
        //                rbn_ImageFormat_bmp.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.jpg:
        //                rbn_ImageFormat_jpg.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.png:
        //                rbn_ImageFormat_png.Checked = true;
        //                break;
        //            case (int)ImageSaveFormat.tiff:
        //                rbn_ImageFormat_tiff.Checked = true;
        //                break;
        //            default:
        //                break;
        //        }
        //        if (!string.IsNullOrEmpty(calib_F.cameraSerial))
        //        {
        //            int index = cbo_cameraSerial.FindString(calib_M.cameraSerialFull);
        //            cbo_cameraSerial.SelectedIndex = index;
        //        }
        //        #endregion

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("输入错误，请检查" + Environment.NewLine + ex.Message);
        //        Log4Helper.WriteLog("FormCalibrationControlToClass", ex);
        //    }
        //}
        private void stationSelect()
        {
            if (rbn_stationFweld.Checked)
            {
                stationNum = 0;
                if (string.IsNullOrEmpty(GlobalImage.cablibData_Fweld.cameraSerial))
                {
                    camControlSetup(false);
                    btn_SoftTrigger.Enabled = false;
                    displalyInfo.displayInfoMain("请先绑定工站对应的相机，再对相机进行操作");
                }
                else
                {
                    camControlSetup(true);
                }
                snapControlSetup(true);
                return;
            }
            if (rbn_stationLweld.Checked)
            {
                stationNum = 1;
                if (string.IsNullOrEmpty(GlobalImage.cablibData_Lweld.cameraSerial))
                {
                    camControlSetup(false);
                    btn_SoftTrigger.Enabled = false;
                    displalyInfo.displayInfoMain("请先绑定工站对应的相机，再对相机进行操作");
                }
                else
                {
                    camControlSetup(true);
                }
                snapControlSetup(true);
                return;
            }
            if (rbn_stationMeasure.Checked)
            {
                stationNum = 2;
                if (string.IsNullOrEmpty(GlobalImage.cablibData_Measure.cameraSerial))
                {
                    camControlSetup(false);
                    btn_SoftTrigger.Enabled = false;
                    displalyInfo.displayInfoMain("请先绑定工站对应的相机，再对相机进行操作");
                }
                else
                {
                    camControlSetup(true);
                }
                snapControlSetup(false);
                return;
            }

        }

        private void camControlSetup(bool isEnabled)
        {
            tbx_exposureSetup.Enabled = isEnabled;
            tbx_frame.Enabled = isEnabled;
            tbx_gain.Enabled = isEnabled;
            cbx_HorizontalFlip.Enabled = isEnabled;
            cbx_VerticalFlip.Enabled = isEnabled;
            tbx_rotateAngle.Enabled = isEnabled;
            btn_ImageRotate.Enabled = isEnabled;
            gbx_grabMode.Enabled = isEnabled;
            btn_StartGrab.Enabled = isEnabled;
            btn_StopGrab.Enabled = isEnabled;
            //btn_SoftTrigger.Enabled = isEnabled;
            btn_saveImage.Enabled = isEnabled;
            btn_openDev.Enabled = isEnabled;
            btn_closeDev.Enabled = isEnabled;
            btn_SnapM1.Enabled = isEnabled;
            btn_SnapM2.Enabled = isEnabled;
        }
        private void snapControlSetup(bool isEnabled)
        {
            btn_ToPositionM1.Enabled = isEnabled;
            btn_ToPositionM2.Enabled = isEnabled;
            //btn_weldCylinder.Enabled = isEnabled;
            //tbx_Mark1RealX.Enabled = isEnabled;
            //tbx_Mark1RealY.Enabled = isEnabled;
            //tbx_Mark2RealX.Enabled = isEnabled;
            //tbx_Mark2RealY.Enabled = isEnabled;
        }
        private void setControlValue(TextBox tbx, int axisNo)
        {
            try
            {
                double F_weld_X = Convert.ToDouble(tbx.Text.Trim());
                double XsoftPosLimit = ((AxisServo)GlobalMotion.mainCard.AxisList[axisNo]).m_SoftPosLimit;
                double XsoftNegLimit = ((AxisServo)GlobalMotion.mainCard.AxisList[axisNo]).m_SoftNegLimit;
                if (F_weld_X < XsoftNegLimit || F_weld_X > XsoftPosLimit)
                {
                    displalyInfo.displayInfoMain("输入的值超过当前轴的软限位");
                }
 
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("请输入符合要求值");
                displalyInfo.displayInfoMain("错误信息是：" + ex.Message);
                Log4Helper.WriteLog("FormType.setControlValue", ex);
            }
        }
        private void btn_ReadImage_Click(object sender, EventArgs e)
        {
            try
            {
                HikVision temp=null;
                Mat tempMat=null;
                string stationName;

                OpenFileDialog typeFile_ofd = new OpenFileDialog();
                typeFile_ofd.Title = "读取本地图像";
                typeFile_ofd.InitialDirectory = Environment.CurrentDirectory;
                typeFile_ofd.Filter = "image Files(*.bmp,*.jpg,*.gif,*.png)|*.bmp;*.jpg;*.gif;*.png|All Files(*.*)|*.*";
                if (typeFile_ofd.ShowDialog() == DialogResult.OK)
                {
                    readImagePath = typeFile_ofd.FileName;
                    tbx_readPath.Text = readImagePath;
                    displalyInfo.displayInfoMain("读取本地图像成功");
                    
                    tempMat = Cv2.ImRead(readImagePath.Trim(), ImreadModes.Grayscale);
                    rbnControlChecked(gbx_station, out stationName);
                    switch (stationName)
                    {
                        case "前焊接工位":
                            displalyImage.displayImage_F(tempMat);
                            GlobalImage.FweldMat = tempMat  ;
                            break;
                        case "后焊接工位":
                            displalyImage.displayImage_L(tempMat);
                            GlobalImage.LweldMat = tempMat;
                            break;
                        case "尺寸测量工位":
                            displalyImage.displayImage_M(tempMat);
                            GlobalImage.MeasureMat = tempMat;
                            break;
                        default:
                            break;
                    }                   
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("读取本地图像失败"+ex.Message);
            }
        }

        private void cbx_VerticalFlip_CheckedChanged(object sender, EventArgs e)
        {
            //ControlToClass(stationNum);
            Mat temp = new Mat();
            temp= opencvProc.Flip(GlobalImage.MeasureMat, cbx_VerticalFlip.Checked, cbx_HorizontalFlip.Checked);
            displalyImage.displayImage_M(temp);
        }

        private void cbx_HorizontalFlip_CheckedChanged(object sender, EventArgs e)
        {
            //ControlToClass(stationNum);
            Mat temp = new Mat();
            temp=opencvProc.Flip(GlobalImage.MeasureMat, cbx_VerticalFlip.Checked, cbx_HorizontalFlip.Checked);
            displalyImage.displayImage_M(temp);
        }

        private void btn_selectCam_Click(object sender, EventArgs e)
        {

        }

        private void rbn_stationFweld_CheckedChanged(object sender, EventArgs e)
        {
            //每次改变radiobutton按钮，会触发两次checkedchanged，如果不加bool变量控制，会导致保存
            //的控件的值不对（旧值），此处要特别注意。我开始以为是变量地址问题，经验证，变量完全不相关
            //也会出现保存值不对的问题
            if (!first_cbx)
            {
                first_cbx = !first_cbx;
            }
            else
            {
                stationSelect();
                ClassToControl(stationNum);
                setTrigger();
            }

        }

        private void tbx_Mark1RealX_TextChanged(object sender, EventArgs e)
        {
            if (stationNum == 0)
            {
                setControlValue(tbx_Mark1RealX, 0);
            }
            if (stationNum == 1)
            {
                setControlValue(tbx_Mark1RealX, 2);
            }
        }

        private void tbx_Mark1RealY_TextChanged(object sender, EventArgs e)
        {
            if (stationNum == 0)
            {
                setControlValue(tbx_Mark1RealY, 1);
            }
            if (stationNum == 1)
            {
                setControlValue(tbx_Mark1RealY, 3);
            }
        }

        private void tbx_Mark2RealX_TextChanged(object sender, EventArgs e)
        {
            if (stationNum == 0)
            {
                setControlValue(tbx_Mark2RealX, 0);
            }
            if (stationNum == 1)
            {
                setControlValue(tbx_Mark2RealX, 2);
            }
        }

        private void tbx_Mark2RealY_TextChanged(object sender, EventArgs e)
        {
            if (stationNum == 0)
            {
                setControlValue(tbx_Mark2RealY, 1);
            }
            if (stationNum == 1)
            {
                setControlValue(tbx_Mark2RealY, 3);
            }
        }

        private void tbx_exposureSetup_TextChanged(object sender, EventArgs e)
        {
            try
            {
                m_exposureTime = Convert.ToInt32(tbx_exposureSetup.Text.Trim());
                if (m_exposureTime >= 10&& m_exposureTime <= 1000000)
                {
                    stationCam(stationNum).setExposureTime(m_exposureTime);
                    //ControlToClass(stationNum);
                }
                
            }
            catch (System.Exception ex)
            {
                //displalyInfo.displayInfoMain("请输入10-1000000的正整数："+ex.Message);
            }
            
        }

        private void btn_updateCamList_Click(object sender, EventArgs e)
        {
            GlobalImage.getCamera.AcqDeviceList(ref imagelist);
            cameraInfo_cbo = new string[imagelist.Count];
            for (int i = 0; i < imagelist.Count; i++)
            {
                GlobalImage.camSerialNo[i] = imagelist[i].m_SerialNO;
                cbo_cameraSerial.Items.Add(imagelist[i].m_SerialNO + " (" + imagelist[i].m_UserDefineName + " ：" + imagelist[i].m_CamName + ")");
                cameraInfo_cbo[i] = imagelist[i].m_SerialNO + " (" + imagelist[i].m_UserDefineName + " ：" + imagelist[i].m_CamName + ")";
            }
        }

        private void cbx_camSerialSelect_CheckedChanged(object sender, EventArgs e)
        {
            if (cbx_camSerialSelect.Checked)
            {
                GlobalVar.isUpdateCamSerial = true;
                displalyInfo.displayInfoMain("已设为选择，请从相机列表中选择当前工位对应的相机");
            }
            else
            {
                GlobalVar.isUpdateCamSerial = false;
                //displalyInfo.displayInfoMain("已设为选择，请从相机列表中选择当前工位对应的相机");
            }
        }

        private void cbo_cameraSerial_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlToClass(stationNum);
            //SerializeFile();
            cbx_camSerialSelect.Checked = false;
            switch (stationNum)
            {
                case 0:
                    if (!string.IsNullOrEmpty( GlobalImage.cablibData_Fweld.cameraSerial))
                    {
                        if (GlobalImage.hik_Fweld == null)
                        {
                            GlobalImage.hik_Fweld = new HikVision(GlobalImage.cablibData_Fweld.cameraSerial);
                            GlobalImage.hik_Fweld.imageOut = visionProc.Fweld;
                        }
                    }                  
                    break;
                case 1:
                    if (!string.IsNullOrEmpty(GlobalImage.cablibData_Lweld.cameraSerial))
                    {
                        if (GlobalImage.hik_Lweld==null)
                        {
                            GlobalImage.hik_Lweld = new HikVision(GlobalImage.cablibData_Lweld.cameraSerial);
                            GlobalImage.hik_Lweld.imageOut = visionProc.Lweld;
                        }                        
                    }                    
                    break;
                case 2:                   
                    if (!string.IsNullOrEmpty(GlobalImage.cablibData_Measure.cameraSerial))
                    {
                        if (GlobalImage.hik_Meausre == null)
                        {
                            GlobalImage.hik_Meausre = new HikVision(GlobalImage.cablibData_Measure.cameraSerial);
                            GlobalImage.hik_Meausre.imageOut = visionProc.measure;
                        }                      
                    }
                    break;
                default:
                    break;
            }
        }
        public void SerializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(calibFilePath, FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Fweld);
                    //GlobalImage.cablibData_Fweld = calib_F;
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Lweld);
                    //GlobalImage.cablibData_Lweld = calib_L;
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Measure);
                    //GlobalImage.cablibData_Measure = calib_M;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("FormType.SerializeFile 序列化异常" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormType.SerializeFile", ex);
            }
        }
        public void SerializeFile(string path)
        {
            try
            {
                using (FileStream fs_serial = new FileStream(path, FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Fweld);
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Lweld);
                    saveFileBF.Serialize(fs_serial, GlobalImage.cablibData_Measure);
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.SerializeFile", ex);
            }
        }
        public void DeserializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(calibFilePath, FileMode.Open))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    GlobalImage.cablibData_Fweld = saveFileBF.Deserialize(fs_serial) as CalibrationData;
                    //GlobalImage.cablibData_Fweld = calib_F;
                    GlobalImage.cablibData_Lweld = saveFileBF.Deserialize(fs_serial) as CalibrationData;
                    //GlobalImage.cablibData_Lweld = calib_L;
                    GlobalImage.cablibData_Measure = saveFileBF.Deserialize(fs_serial) as CalibrationData;
                    //GlobalImage.cablibData_Measure = calib_M;
                    ClassToControl(stationNum);
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.DeserializeFile", ex);
            }
        }
        private HikVision stationCam(int station)
        {
            try
            {
                HikVision temp;
                switch (station)
                {
                    case 0:
                        temp = GlobalImage.hik_Fweld;
                        break;
                    case 1:
                        temp = GlobalImage.hik_Lweld;
                        break;
                    case 2:
                        temp = GlobalImage.hik_Meausre;
                        break;
                    default:
                        temp = GlobalImage.hik_Fweld;
                        break;
                }
                return temp;
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("工站相机选择错误："+ex.Message);
                return null;
            }
            
        }

        private void tbx_gain_TextChanged(object sender, EventArgs e)
        {
            try
            {
                m_gain = Convert.ToSingle(tbx_gain.Text.Trim());
                if (m_gain >= 1 && m_gain <= 20)
                {
                    stationCam(stationNum).SetParamter(m_exposureTime,m_gain,m_frame);
                    //ControlToClass(stationNum);
                }
                else
                {
                    displalyInfo.displayInfoMain("请输入1-20的数");
                }
            }
            catch (System.Exception ex)
            {
                //displalyInfo.displayInfoMain("请输入1-20的数：" + ex.Message);
            }
        }

        private void tbx_frame_TextChanged(object sender, EventArgs e)
        {
            try
            {
                m_frame = Convert.ToSingle(tbx_gain.Text.Trim());
                if (m_frame >= 1 && m_frame <= 100)
                {
                    stationCam(stationNum).SetParamter(m_exposureTime, m_gain, m_frame);
                    //ControlToClass(stationNum);
                }
                else
                {
                    displalyInfo.displayInfoMain("请输入1-100的数");
                }
            }
            catch (System.Exception ex)
            {
                //displalyInfo.displayInfoMain("请输入1-100的数：" + ex.Message);
            }
        }

        private void tbx_rotateAngle_TextChanged(object sender, EventArgs e)
        {
            try
            {
                m_rotateAngle = Convert.ToSingle(tbx_rotateAngle.Text.Trim());
                if (m_rotateAngle<-360||m_rotateAngle>360)
                {
                    displalyInfo.displayInfoMain("旋转角度是（-360）--（+360）");
                }
               
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("请输入(-360)--(360)的数：" + ex.Message);
            }
        }


        private void btn_camCaliSave_Click(object sender, EventArgs e)
        {
            if (File.Exists(calibFilePath))
            {
                File.Delete(calibFilePath);
            }
            ControlToClass(stationNum);
            SerializeFile();
            displalyInfo.displayInfoMain("保存更改完成");
        }

        private void ImageMode(int mode)
        {
            switch (stationNum)
            {
                case 0:
                    GlobalImage.imageProcMode_F = mode;
                    break;
                case 1:
                    GlobalImage.imageProcMode_L = mode;
                    break;
                case 2:
                    GlobalImage.imageProcMode_M = mode;
                    break;
                default:
                    break;
            }
        }
        private void btn_StartGrab_Click(object sender, EventArgs e)
        {
            ImageMode((int)e_imageProcMode.justDisplay);
            HikVision temp;
            temp = selectCam();
            if (temp==null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            if (!temp.m_bConnected)
            {
                temp.ConnectDev();
            }
            if (!temp.m_bGrabbed)
            {
                temp.StartGrab();
                displalyInfo.displayInfoMain("开始采集");               
            }
            if (rbn_grabContunial.Checked)
            {
                btn_SoftTrigger.Enabled = false;
            }
            else
            {
                btn_SoftTrigger.Enabled = true;
            }
            btn_StartGrab.Enabled = false;
            btn_StopGrab.Enabled = true;
            btn_closeDev.Enabled = true;
            btn_openDev.Enabled = false;
            btn_saveImage.Enabled = true;


        }

        private void rbn_grabContunial_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                setTrigger();
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("rbn_grabContunial_CheckedChanged:"+ex.Message);
            }

        }
        private void setTrigger()
        {
            HikVision temp;
            temp = selectCam();
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            if (rbn_grabContunial.Checked)
            {
                temp.SetTriggerMode(TriggerMode.continual);
                btn_SoftTrigger.Enabled = false;
            }
            else
            {
                temp.SetTriggerMode(TriggerMode.softTrigger);
                btn_SoftTrigger.Enabled = true;
            }
            if (temp.m_bConnected)
            {
                btn_openDev.Enabled = false;
                btn_closeDev.Enabled = true;
            }
            else
            {
                btn_closeDev.Enabled = false;
                btn_openDev.Enabled = true;
            }
            if (temp.m_bGrabbed)
            {
                btn_StartGrab.Enabled = false;
                btn_StopGrab.Enabled = true;
                btn_saveImage.Enabled = true;
            }
            else
            {
                btn_StartGrab.Enabled = true;
                btn_StopGrab.Enabled = false   ;
                btn_saveImage.Enabled = false;
            }
        }
        private HikVision selectCam()
        {
            try
            {
                HikVision temp=null;
                switch (stationNum)
                {
                    case 0:
                        if (GlobalImage.hik_Fweld != null)
                        {
                            temp = GlobalImage.hik_Fweld;
                        }
                        break;
                    case 1:
                        if (GlobalImage.hik_Lweld != null)
                        {
                            temp = GlobalImage.hik_Lweld;
                        }
                        break;
                    case 2:
                        if (GlobalImage.hik_Meausre != null)
                        {
                            temp = GlobalImage.hik_Meausre;
                        }
                        break;
                    default:
                        break;
                }
                return temp;
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("FormCalibration.selectCam 出错："+ex.Message);
                return null;
            }
            
        }
        private HikVision selectCam(ref Mat output,ref CalibrationData calib)
        {
            try
            {
                HikVision temp = null;
                switch (stationNum)
                {
                    case 0:
                        if (GlobalImage.hik_Fweld != null)
                        {
                            temp = GlobalImage.hik_Fweld;
                            output = GlobalImage.FweldMat;
                            calib = GlobalImage.cablibData_Fweld;
                        }
                        break;
                    case 1:
                        if (GlobalImage.hik_Lweld != null)
                        {
                            temp = GlobalImage.hik_Lweld;
                            output = GlobalImage.LweldMat;
                            calib = GlobalImage.cablibData_Lweld;
                        }
                        break;
                    case 2:
                        if (GlobalImage.hik_Meausre != null)
                        {
                            temp = GlobalImage.hik_Meausre;
                            output = GlobalImage.MeasureMat;
                            calib = GlobalImage.cablibData_Measure;
                        }
                        break;
                    default:
                        break;
                }
                return temp;
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("FormCalibration.selectCam 出错：" + ex.Message);
                return null;
            }

        }
        private void btn_StopGrab_Click(object sender, EventArgs e)
        {
            HikVision temp;
            temp = selectCam();
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            if (temp.m_bGrabbed)
            {
                temp.stopGrab();
                displalyInfo.displayInfoMain("停止采集");
            }
            btn_StartGrab.Enabled = true;
            btn_StopGrab.Enabled = false;
            btn_saveImage.Enabled = false;
            btn_SoftTrigger.Enabled = false;
        }

        private void btn_saveImage_Click(object sender, EventArgs e)
        {
            HikVision temp;
            Mat saveMat = null;
            CalibrationData calibdata = null;
            temp = selectCam(ref saveMat,ref calibdata);
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            if (saveMat == null)
            {
                displalyInfo.displayInfoMain("没有采集到数据，请先采集再保存");
                return;
            }
            if (calibdata == null)
            {
                displalyInfo.displayInfoMain("相机标定设置数据为空，请先保存相机标定设置");
                return;
            }
            string imageFormatName = ".bmp";
            string path;
            string savePath;
            string saveName;
            if (string.IsNullOrEmpty(calibdata.saveFilePath))
            {
                savePath = Application.StartupPath;
            }
            else
            {
                savePath = calibdata.saveFilePath;
            }
            switch (calibdata.saveImageFormat)
            {
                case (int)ImageSaveFormat.bmp:
                    imageFormatName = ".bmp";
                    break;
                case (int)ImageSaveFormat.jpg:
                    imageFormatName = ".jpg";
                    break;
                case (int)ImageSaveFormat.png:
                    imageFormatName = ".png";
                    break;
                case (int)ImageSaveFormat.tiff:
                    imageFormatName = ".tiff";
                    break;
                default:
                    break;
            }
            
            rbnControlChecked(gbx_station, out path);
            saveName = savePath + "\\" + path + DateTime.Now.ToString("yyyyMMdd-HHmmssfff") + imageFormatName;
            opencvProc.saveImage(saveMat, saveName);
            //displalyInfo.displayInfoMain
        }

        private void btn_openDev_Click(object sender, EventArgs e)
        {
            HikVision temp;
            temp = selectCam();
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            if (!temp.m_bConnected)
            {
                temp.ConnectDev();

            }
            btn_openDev.Enabled = false;
            btn_closeDev.Enabled = true;
            btn_StartGrab.Enabled = true;
            btn_StopGrab.Enabled = false;
            btn_saveImage.Enabled = true;
            if (rbn_grabContunial.Checked)
            {
                btn_SoftTrigger.Enabled = false;
            }
            else
            {
                btn_SoftTrigger.Enabled = true;
            }
        }

        private void btn_closeDev_Click(object sender, EventArgs e)
        {
            HikVision temp;
            temp = selectCam();
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            //temp.stopGrab();
            if (temp.m_bConnected)
            {
                temp.DisConnectDev();

            }
            btn_closeDev.Enabled = false;
            btn_openDev.Enabled = true;
            btn_StartGrab.Enabled = false;
            btn_SoftTrigger.Enabled = false;
            btn_saveImage.Enabled = false;
            btn_StopGrab.Enabled = false;
        }

        private void btn_SoftTrigger_Click(object sender, EventArgs e)
        {
            ImageMode((int)e_imageProcMode.justDisplay);
            HikVision temp;
            temp = selectCam();
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return;
            }
            temp.softTrigger();
        }

        private void btn_ToPositionM1_Click(object sender, EventArgs e)
        {
            try
            {
                double marker1X = 0;
                double marker1Y = 0;
                marker1X = Convert.ToDouble(tbx_Mark1RealX.Text.Trim());
                marker1Y = Convert.ToDouble(tbx_Mark1RealY.Text.Trim());

                if (stationNum==0)
                {
                    Task.Factory.StartNew(() =>
                    {
                        GlobalMotion.toPosition(marker1X, marker1Y, 0, 1);
                    });
                }
               if (stationNum==1)
               {
                    Task.Factory.StartNew(() =>
                    {
                        GlobalMotion.toPosition(marker1X, marker1Y, 2, 3);
                    });
                }               
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("运行到marker1XY位置出错："+ex.Message);
            }
            
        }

        private void btn_ToPositionM2_Click(object sender, EventArgs e)
        {
            try
            {
                double marker2X = 0;
                double marker2Y = 0;
                marker2X = Convert.ToDouble(tbx_Mark2RealX.Text.Trim());
                marker2Y = Convert.ToDouble(tbx_Mark2RealY.Text.Trim());

                if (stationNum == 0)
                {
                    Task.Factory.StartNew(() =>
                    {
                        GlobalMotion.toPosition(marker2X, marker2Y, 0, 1);
                    });
                }
                if (stationNum == 1)
                {
                    Task.Factory.StartNew(() =>
                    {
                        GlobalMotion.toPosition(marker2X, marker2Y, 2, 3);
                    });
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("运行到marker2XY位置出错：" + ex.Message);
            }
        }

        private void btn_getPositionM1_Click(object sender, EventArgs e)
        {
            try
            {
                if (stationNum == 0)
                {
                    GlobalMotion.getAxisAndSet(tbx_Mark1RealX, tbx_Mark1RealY, 0, 1);
                }
                if (stationNum == 1)
                {
                    GlobalMotion.getAxisAndSet(tbx_Mark1RealX, tbx_Mark1RealY, 2, 3);
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("获取marker1XY位置出错：" + ex.Message);
            }
        }

        private void btn_getPositionM2_Click(object sender, EventArgs e)
        {
            try
            {
                if (stationNum == 0)
                {
                    GlobalMotion.getAxisAndSet(tbx_Mark2RealX, tbx_Mark2RealY, 0, 1);
                }
                if (stationNum == 1)
                {
                    GlobalMotion.getAxisAndSet(tbx_Mark2RealX, tbx_Mark2RealY, 2, 3);
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("获取marker2XY位置出错：" + ex.Message);
            }
        }

        private void btn_SnapM1_Click(object sender, EventArgs e)
        { 
            Task.Run(() => softTask(tbx_Mark1ImageX,tbx_Mark1ImageY));

        }

        private async Task<double[]> softTask(TextBox tb1,TextBox tb2)
        {
            Stopwatch softTimeout = new Stopwatch();
            Task<double[]> taskTemp=null;
            double[] xyTemp = new double[2];
            ImageMode((int)e_imageProcMode.calibrate);
            HikVision temp;
            temp = selectCam();//判断是选择的哪个相机
            if (temp == null)
            {
                displalyInfo.displayInfoMain("相机选择出错");
                return null;
            }

            temp.softTrigger();//软触发采集
            softTimeout.Restart();
            while (true)
            {
                Thread.Sleep(5);
                switch (stationNum)
                {
                    case 0:
                        taskTemp = GlobalImage.Fcalib_task;
                        break;
                    case 1:
                        taskTemp = GlobalImage.Lcalib_task;
                        break;
                    case 2:
                        taskTemp = GlobalImage.Mcalib_task;
                        break;
                    default:
                        break;
                }
                if (softTimeout.ElapsedMilliseconds > 2000)
                {
                    displalyInfo.displayInfoMain("标定图像处理超时");
                    return null;
                }
                if (taskTemp == null)
                {
                    continue;
                }
                else
                {
                    break;
                }
               
            }
            xyTemp = await taskTemp;
            if (xyTemp == null)
            {
                return null;
            }
            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    tb1.Text = xyTemp[0].ToString("#0.000");
                    tb2.Text = xyTemp[1].ToString("#0.000");
                }));
            }
            else
            {
                tb1.Text = xyTemp[0].ToString("#0.000");
                tb2.Text = xyTemp[1].ToString("#0.000");
            }
            switch (stationNum)
            {
                case 0:
                    GlobalImage.Fcalib_task=null;
                    break;
                case 1:
                    GlobalImage.Lcalib_task=null;
                    break;
                case 2:
                    GlobalImage.Mcalib_task=null;
                    break;
                default:
                    break;
            }
            return xyTemp;
           
        }

        private void btn_SnapM2_Click(object sender, EventArgs e)
        {
            Task.Run(() => softTask(tbx_Mark2ImageX, tbx_Mark2ImageY));
        }

        public double[] ImageToReal()
        {
            double RealX1 = 0.0, RealY1 = 0.0, RealX2 = 0.0, RealY2 = 0.0, MarkX1 = 0.0, MarkY1 = 0.0, MarkX2 = 0.0, MarkY2 = 0.0;
            double RealLength = 0.0, ImageLength = 0.0;

            try
            {
                if (InvokeRequired)
                {
                    tbx_camCaliPixelReal.Invoke(new MethodInvoker(() =>
                    {
                        RealX1 = Convert.ToDouble(tbx_Mark1RealX.Text);
                        RealY1 = Convert.ToDouble(tbx_Mark1RealY.Text);
                        RealX2 = Convert.ToDouble(tbx_Mark2RealX.Text);
                        RealY2 = Convert.ToDouble(tbx_Mark2RealY.Text);
                        MarkX1 = Convert.ToDouble(tbx_Mark1ImageY.Text);
                        MarkY1 = Convert.ToDouble(tbx_Mark1ImageX.Text);
                        MarkX2 = Convert.ToDouble(tbx_Mark2ImageY.Text);
                        MarkY2 = Convert.ToDouble(tbx_Mark2ImageX.Text);
                        RealLength = Math.Sqrt(Math.Pow((RealX2 - RealX1), 2) + Math.Pow((RealY2 - RealY1), 2));
                        ImageLength = Math.Sqrt(Math.Pow((MarkX2 - MarkX1), 2) + Math.Pow((MarkY2 - MarkY1), 2));
                        tbx_camCaliPixelReal.Text = (ImageLength / RealLength).ToString();
                    }));
                }
                else
                {
                    RealX1 = Convert.ToDouble(tbx_Mark1RealX.Text);
                    RealY1 = Convert.ToDouble(tbx_Mark1RealY.Text);
                    RealX2 = Convert.ToDouble(tbx_Mark2RealX.Text);
                    RealY2 = Convert.ToDouble(tbx_Mark2RealY.Text);
                    MarkX1 = Convert.ToDouble(tbx_Mark1ImageY.Text);
                    MarkY1 = Convert.ToDouble(tbx_Mark1ImageX.Text);
                    MarkX2 = Convert.ToDouble(tbx_Mark2ImageY.Text);
                    MarkY2 = Convert.ToDouble(tbx_Mark2ImageX.Text);
                    RealLength = Math.Sqrt(Math.Pow((RealX2 - RealX1), 2) + Math.Pow((RealY2 - RealY1), 2));
                    ImageLength = Math.Sqrt(Math.Pow((MarkX2 - MarkX1), 2) + Math.Pow((MarkY2 - MarkY1), 2));
                    tbx_camCaliPixelReal.Text = (ImageLength / RealLength).ToString("#0.000");
                }
                PixelToReal = ImageLength / RealLength;
                double[] realCoord = { RealX1, RealY1, RealX2, RealY2 };
                double[] imageCoord = { MarkX1 / PixelToReal, MarkY1 / PixelToReal, MarkX2 / PixelToReal, MarkY2 / PixelToReal };
                double[] ResultConvert = MathNetHelper.CoordinateTransform(imageCoord, realCoord);
                //return Math.Round((ImageLength / RealLength), 4);
                return ResultConvert;
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog(typeof(FormCalibration), ex);
                return null;
            }

        }
    }
}
